<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="Path" prop="name">
        <el-input
          v-model="queryParams.path"
          placeholder="请输入Path"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['easyapi:apiconfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['easyapi:apiconfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['easyapi:apiconfig:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExportJson"
          v-hasPermi="['easyapi:apiconfig:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleImportJson"
          v-hasPermi="['easyapi:apiconfig:add']"
        >导入</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="apiconfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="path" align="center" prop="path" />
      <el-table-column label="Content-Type" align="center" prop="contentType" :formatter="contentTypeFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['easyapi:apiconfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['easyapi:apiconfig:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleCopy(scope.row)"
            v-hasPermi="['easyapi:apiconfig:add']"
          >复制</el-button>
          <el-button
            v-if="scope.row.status==0"
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleOffline(scope.row.id)"
            v-hasPermi="['easyapi:apiconfig:edit']"
          >下线</el-button>

          <el-button
            v-if="scope.row.status==1"
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleOnline(scope.row.id)"
            v-hasPermi="['easyapi:apiconfig:edit']"
          >上线</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog title="JSON" :visible.sync="jsonOpen" width="800px" append-to-body>
      <el-form ref="jsonForm" :model="jsonForm" label-width="80px">
        <el-form-item label="" prop="json">
          <el-input v-model="jsonForm.json"  :autosize="{ minRows: 2, maxRows: 100}" type="textarea" :disabled="jsonCanEdit" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!this.jsonCanEdit" type="primary" @click="handleJsonConfirm">保存</el-button>
        <el-button type="primary" @click="handleClose">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改接口配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述" prop="note">
          <el-input v-model="form.note" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="执行类型" prop="executeType">
          <el-select v-model="form.executeType" placeholder="请选择执行类型">
            <el-option
              key="sql"
              label="sql"
              value="sql"
            ></el-option>
            <el-option
              key="http"
              label="http"
              value="http"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.executeType=='sql'" label="是否分页" prop="pagingFlag">
          <el-switch
            v-model="form.pagingFlag"
            :active-value='1'
            :inactive-value='0'
          ></el-switch>
        </el-form-item>
        <el-form-item label="是否计数" prop="isCalNum">
          <el-switch
            v-model="form.isCalNum"
            :active-value='1'
            :inactive-value='0'
          ></el-switch>
        </el-form-item>
        <el-form-item label="是否缓存" prop="cacheable">
          <el-switch
            v-model="form.cacheable"
            :active-value='"1"'
            :inactive-value='"0"'
          ></el-switch>
        </el-form-item>
        <el-form-item label="path" prop="path">
          <el-input v-model="form.path" placeholder="请输入path" />
        </el-form-item>
        <el-form-item v-if="form.contentType != 'application/json'" label="参数" prop="params">
          <el-input v-model="form.params" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item v-if="form.contentType == 'application/json'" label="参数" prop="jsonParam">
          <el-input v-model="form.jsonParam" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="参数描述" prop="paramsDesc">
          <el-input v-model="form.paramsDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开放数据集类型" prop="openDataType">
          <el-select v-model="form.openDataType" placeholder="请选择开放数据集类型">
            <el-option
              v-for="dict in openDataTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Content-Type" prop="contentType">
          <el-select v-model="form.contentType" placeholder="请选择Content-Type">
            <el-option
              v-for="dict in contentTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="form.executeType" prop="task">
          <el-input v-model="form.task" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="导出模板" prop="template">
          <el-input v-model="form.template" />
          <el-upload
            class="upload-demo"
            :action="action"
            :limit="1"
            :file-list="fileList"
            :show-file-list="true"
            :on-success = "uploadSuccess"
            :headers = "actionHeaders"
            >
            <!-- action="/api/file/fileUpload" -->
            <el-button class="btn"><i class="el-icon-paperclip"></i>上传附件</el-button>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApiconfig, getApiconfig, delApiconfig, addApiconfig, updateApiconfig, exportApiconfig } from "@/api/easyapi/apiconfig";
import { uploadFile } from "@/api/common/common"
import FormData from 'form-data'
import { getToken } from '@/utils/auth'
export default {
  name: "Apiconfig",
  data() {
    return {
      fileList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 接口配置表格数据
      apiconfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      jsonOpen: false,
      jsonForm:{
        json: null
      },
      jsonCanEdit: true,
      // 状态字典
      statusOptions: [],
      // Content-Type字典
      contentTypeOptions: [],
      openDataTypeOptions:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        path: null
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        contentType: [
          { required: true, message: "Content-Type不能为空", trigger: "change" }
        ],
        task: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("content_type").then(response => {
      this.contentTypeOptions = response.data;
    });
    this.getDicts("open_data_type").then(resp => {
      this.openDataTypeOptions = resp.data
    })
  },
  mounted(){

  },
  computed: {
    action(){
      return `${process.env.VUE_APP_BASE_API}/common/upload`
    },
    actionHeaders(){
      return {Authorization: 'Bearer ' + getToken()}
    }
  },
  methods: {
    uploadTemplate(req){
      let fileData = new FormData()
      fileData.append('file',req.file)
      uploadFile(fileData).then(res =>{
        console.log(res)
      })
    },
    uploadSuccess(resp, file, fileList){
      debugger
      fileList[0].name= resp.fileName.replace('profile','data/szrz-files')
      this.form.template = resp.fileName.replace('profile','data/szrz-files')
    },
    /** 查询接口配置列表 */
    getList() {
      this.loading = true;
      listApiconfig(this.queryParams).then(response => {
        this.apiconfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // Content-Type字典翻译
    contentTypeFormat(row, column) {
      return this.selectDictLabel(this.contentTypeOptions, row.contentType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //上线接口
    handleOnline(id){
      let data = {
        id:id,
        status: 0
      }
      updateApiconfig(data).then(response =>{
        this.msgSuccess("上线成功")
        this.getList()
      });
    },
    //下线接口
    handleOffline(id){
      let data = {
        id:id,
        status: 1
      }
      updateApiconfig(data).then(response =>{
        this.msgSuccess("下线成功")
        this.getList()
      });
    },
    // 表单重置
    reset() {
      this.fileList = []
      this.form = {
        id: null,
        name: null,
        note: null,
        path: null,
        params: null,
        jsonParam: null,
        status: 0,
        access: null,
        groupId: null,
        contentType: null,
        task: null,
        createUserId: null,
        createTime: null,
        updateTime: null,
        pagingFlag: null,
        paramsDesc: null,
        isCalNum: null,
        openDataType: null,
        cacheable: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加接口配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getApiconfig(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改接口配置";
      });
    },
    handleCopy(row) {
      this.reset();
      const id = row.id || this.ids
      getApiconfig(id).then(response => {
        this.form = {...response.data};
        this.form.id = null;
        this.open = true;
        this.title = "修改接口配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateApiconfig(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApiconfig(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除接口配置编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delApiconfig(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有接口配置数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportApiconfig(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    handleExportJson(row){
      const ids = row.id || this.ids;

      const exportList = this.apiconfigList.filter(one =>{
        return ids.includes(one.id)
      })
      this.jsonForm={
        json:JSON.stringify(exportList,null, '\t')
      }
      this.jsonOpen = true;
    },
    handleClose(){
      this.jsonForm = {}
      this.jsonOpen = false;
      this.jsonCanEdit = true;
    },
    handleImportJson(){
      this.jsonForm = {}
      this.jsonCanEdit = false;
      this.jsonOpen = true;
    },
    handleJsonConfirm(){
      JSON.parse(this.jsonForm.json).forEach(one =>{
        if (one.id != null) {
            updateApiconfig(one).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApiconfig(one).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
      })

      this.handleClose()
    }
  }
};
</script>
